package weaver.interfaces.jz.job;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.util.ServiceUtil;
import com.engine.jz.service.JzjgService;
import com.engine.jz.service.impl.JzjgServiceImpl;
import com.engine.jz.util.CommonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.hrm.User;
import weaver.interfaces.schedule.BaseCronJob;
import weaver.interfaces.workflow.action.Action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/**
 * @version 1.0
 * @Title ecology-9
 * @Company 泛微软件
 * @CreateDate 2024/12/2
 * @Description 人员离职同步删除设备上的人员
 * @Author AdminZm
 */
public class HrmDepartSyncDeviceJob extends BaseCronJob {

    BaseBean baseBean = new BaseBean();

    public JzjgService getJzjgService(User user) {
        return ServiceUtil.getService(JzjgServiceImpl.class, user);
    }

    @Override
    public void execute() {
        baseBean.writeLog("HrmDepartSyncDeviceJob start.");
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        try {
            String today = DateUtil.format(new Date(), "yyyy-MM-dd");
            User user = new User();
            user.setLanguage(7);
            user.setLoginid("sysadmin");
            user.setUid(1);
            String modeId = rs.getPropValue("jzjg_zm_prop", "tssbjl_mode_id");
            String cusId = rs.getPropValue("jzjg_zm_prop", "tssbjl_cus_id");
            SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm:ss");
            String tbIp = rs.getPropValue("jzjg_zm_prop", "tb_ip");
            // 获取考勤设备ip
            Map<String, String> ipMapKs = new HashMap<>();
            Map<String, String> ipMapTb = new HashMap<>();
            Map<String, String> ipMapZk = new HashMap<>();
            rs.execute("SELECT * FROM uf_kqsbdzgxgljmb WHERE sbip is not null");
            while (rs.next()) {
                String id = rs.getString("id");
                String sbip = rs.getString("sbip");
                String sblx = rs.getString("sblx");
                String sbxlh = rs.getString("sbxlh");
                if (StringUtils.isEmpty(id)) {
                    continue;
                }
                if (StringUtils.equals(sblx, "1") && StringUtils.isNotEmpty(sbip)) {
                    ipMapKs.put(id, sbip);
                }
                if (StringUtils.equals(sblx, "0")) {
                    if (StringUtils.isEmpty(sbxlh)) {
                        continue;
                    }
                    ipMapTb.put(id, tbIp + "_" + sbxlh);
                }
                if (StringUtils.equals(sblx, "2")  && StringUtils.isNotEmpty(sbip)) {
                    ipMapZk.put(id, sbip);
                }
            }
            if (CollectionUtils.isEmpty(ipMapKs) && CollectionUtils.isEmpty(ipMapTb) && CollectionUtils.isEmpty(ipMapZk)) {
                baseBean.writeLog("HrmDepartSyncDeviceJob ip info is null.");
                return;
            }

            Set<String> idSet = new HashSet<>();
            String querySql = "SELECT * FROM uf_lzryxxtzjmb  WHERE lzrq < '" + today + "' AND (sfytb is null or sfytb != 1)";
            rs.execute(querySql);
            while (rs.next()) {
                String id = rs.getString("id");
                String gh1 = rs.getString("gh");

                // 根据工号获取loginid
                if (StringUtils.isEmpty(gh1)) {
                    baseBean.writeLog("HrmDepartSyncDeviceJob gh is null.");
                    continue;
                }
                String gh = null;
                rs1.executeQuery("SELECT loginid FROM hrmresource WHERE workcode = ?", gh1);
                if (rs1.next()) {
                    gh = rs1.getString("loginid");
                }
                if (StringUtils.isEmpty(gh)) {
                    baseBean.writeLog("HrmDepartSyncDeviceJob loginid is null.");
                    continue;
                }

                gh = CommonUtil.removeLeadingZeros(gh);
                if (StringUtils.isEmpty(gh)) {
                    baseBean.writeLog("HrmDeploySyncDeviceJob gh is null.");
                    continue;
                }

                boolean sfytb = false;
                // 旷视
                if (!CollectionUtils.isEmpty(ipMapKs)) {
                    Map<String, Object> ksParamMap = new HashMap<>();
                    ksParamMap.put("id", gh);
                    for (Map.Entry<String, String> entry : ipMapKs.entrySet()) {
                        String sbid = entry.getKey();
                        String sbip = entry.getValue();
                        String uuid = UUID.randomUUID() + "-" + gh;
                        rs1.executeUpdate("INSERT INTO uf_tssbjlglb (sb,lztzid,qqcsjmq,zt,tslx, formmodeid,MODEUUID,modedatacreater," +
                                        "modedatacreatertype, modedatacreatedate, modedatacreatetime) VALUES (?,?,?,?,?,?,?,?,?,?,?)",
                                sbid, id, JSONObject.toJSONString(ksParamMap), "0", "2", modeId, uuid, "1",
                                "0", sdfDate.format(new Date()), sdfTime.format(new Date()));
                        String dataId = null;
                        rs1.executeQuery("SELECT id FROM uf_tssbjlglb WHERE MODEUUID = ?", uuid);
                        if (rs1.next()) {
                            dataId = rs1.getString("id");
                        }
                        sfytb = true;
                        getJzjgService(user).delHrmInKs(sbip, ksParamMap, dataId);
                    }
                }

                // 天波
                if (!CollectionUtils.isEmpty(ipMapTb)) {
                    for (Map.Entry<String, String> entry : ipMapTb.entrySet()) {
                        String sbid = entry.getKey();
                        String value = entry.getValue();
                        String ip = value.split("_")[0];
                        String sn = value.split("_")[1];

                        Map<String, Object> tbParamMap = new HashMap<>();
                        tbParamMap.put("SN", sn);
                        tbParamMap.put("taskId", System.currentTimeMillis());

                        List<Map<String, String>> mapList = new ArrayList<>();
                        Map<String, String> mapTemp = new HashMap<>();
                        mapTemp.put("pin", gh);
                        mapList.add(mapTemp);
                        tbParamMap.put("Data", mapList);

                        String uuid = UUID.randomUUID() + "-" + gh;
                        rs1.executeUpdate("INSERT INTO uf_tssbjlglb (sb,lztzid,qqcsjmq,zt,tslx, formmodeid,MODEUUID,modedatacreater," +
                                        "modedatacreatertype, modedatacreatedate, modedatacreatetime) VALUES (?,?,?,?,?,?,?,?,?,?,?)",
                                sbid, id, JSONObject.toJSONString(tbParamMap), "0", "2", modeId, uuid, "1",
                                "0", sdfDate.format(new Date()), sdfTime.format(new Date()));
                        String dataId = null;
                        rs1.executeQuery("SELECT id FROM uf_tssbjlglb WHERE MODEUUID = ?", uuid);
                        if (rs1.next()) {
                            dataId = rs1.getString("id");
                        }
                        sfytb = true;
                        getJzjgService(user).delHrmInTb(ip, tbParamMap, dataId);
                    }
                }

                if (sfytb) {
                    idSet.add(id);
                }
            }

            if (!CollectionUtils.isEmpty(idSet)) {
                rs.execute("update uf_lzryxxtzjmb set sfytb = 1 where id in (" + String.join(",", idSet) + ")");
            }
        } catch (Exception e) {
            baseBean.writeLog("HrmDepartSyncDeviceJob error:" + e);
        }
    }
}
